import { io, Socket } from 'socket.io-client'

const enableSocket = import.meta.env.VITE_ENABLE_SOCKET === 'true'

export interface IncomingMessagePayload {
  room?: string
  device_id?: string
  wx_id?: string
  from?: string
  to?: string
  content?: string
  type?: number
  timestamp?: string | number
  [key: string]: any
  is_self_message: boolean
}
export interface IncomingRAGMessagePayload {
  room?: string
  to?: string
  content?: string
  type?: number
  timestamp?: string | number
  [key: string]: any
}
class SocketService {
  private socket: Socket | null = null
  private isConnected = false

  connect(token?: string): Socket | null {
    if (!enableSocket) {
      console.warn('[socket] 已禁用，跳过连接')
      return null
    }
    if (this.socket && this.isConnected) return this.socket

    // 从环境变量获取WebSocket服务地址，默认使用当前主机的WebSocket协议
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const host = window.location.host;
    const socketUrl = `${protocol}//${host}`;
    console.log("实际使用的 socketUrl:", socketUrl); // 打印到控制台
    this.socket = io(socketUrl, {
      path: '/socket.io',
      transports: ['websocket'],
      autoConnect: true,
      withCredentials: true,
      auth: token ? { token } : undefined
    })

    ;(window as any).__s = this.socket

    this.socket.on('connect', () => {
      this.isConnected = true
      console.log('[socket] connected:', this.socket?.id)
    })

    this.socket.on('disconnect', (reason) => {
      this.isConnected = false
      console.log('[socket] disconnected:', reason)
    })

    this.socket.on('connect_error', (err) => {
      console.error('[socket] connect_error:', err)
    })

    return this.socket
  }
  // 添加发送消息方法
  public sendMessage(payload: any): void {
    if (this.socket && this.socket.connected) {
      this.socket.emit('send_message', payload);
      console.log('[socket] send_message:', payload);
    } else {
      console.error('WebSocket未连接，无法发送消息');
      // 这里可以添加重连逻辑
    }
  }
  disconnect() {
    if (this.socket) {
      this.socket.disconnect()
      this.socket = null
      this.isConnected = false
    }
  }

  joinRoom(roomId: string) {
    if (!this.socket) return
    const emitJoin = () => {
      console.log('[socket] join room:', roomId)
      this.socket!.emit('join', { room: roomId })

    }
    if (this.isConnected) emitJoin()
    else this.socket.once('connect', emitJoin)
  }

  leaveRoom(roomId: string) {
    if (!this.socket) return
    console.log('[socket] leave room:', roomId)
    this.socket.emit('leave', { room: roomId })

  }
  ragHandeler(payload: IncomingRAGMessagePayload){
    payload.is
  }
  onRagMessage(handler: (payload: IncomingMessagePayload) => void) {
    if (!this.socket) return
    this.socket.on('rag_message', handler)
  }

  offNewMessage(handler?: (payload: IncomingMessagePayload) => void) {
    if (!this.socket) return
    if (handler) this.socket.off('new_message', handler)
    else this.socket.off('new_message')
  }
}

export const socketService = new SocketService()